package com.jake.rabbit.bpm.controller;

import com.jake.rabbit.bpm.consumer.ResponseConsumer;
import com.jake.rabbit.bpm.producer.RequestProducer;
import com.jake.rabbit.util.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

import static com.jake.rabbit.constant.KeyConstants.*;
import static com.jake.rabbit.constant.QueueConstants.REQUEST_QUEUE;

@RestController
@RequestMapping(value = "attendance")
@Slf4j
public class AttendanceController {

    @Autowired
    private RequestProducer requestProducer;

    @Autowired
    private ResponseConsumer responseConsumer;

    @PostMapping(value = "record")
    public Map<String, Object> getAttendanceRecord(@RequestBody Map<String, Object> requestMap) {
        String requestId = UUID.randomUUID().toString();
        int requestQueueNumber = RandomUtils.nextInt(1, 6);
        requestMap.put(REQUEST_ID, requestId);
        requestMap.put(REQUEST_QUEUE_NUMBER, requestQueueNumber);
        requestProducer.sendRequestMap(REQUEST_QUEUE + requestQueueNumber, requestMap);

        Map<String, Object> responseMap = responseConsumer.getResponseMap();
        while (responseMap == null) {
            ThreadUtils.sleep(20);
            responseMap = responseConsumer.getResponseMap();
        }

        String responseId = (String) responseMap.get(RESPONSE_ID);
        Integer responseQueueNumber = (Integer) responseMap.get(RESPONSE_QUEUE_NUMBER);
        while (!(StringUtils.equals(requestId, responseId) && requestQueueNumber == responseQueueNumber)) {
            ThreadUtils.sleep(20);
            responseMap = responseConsumer.getResponseMap();
            responseId = (String) responseMap.get(RESPONSE_ID);
            responseQueueNumber = (Integer) responseMap.get(RESPONSE_QUEUE_NUMBER);
        }

        responseMap.remove("responseQueueNumber");
        responseMap.remove("responseId");

        return responseMap;
    }

}
